package com.tonghl.juc.lock_study.code;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by tonghl
 * 自旋锁
 * 题目：手写自旋锁
 * 好处：循环比较直到成功为止，没有类似wait的阻塞
 *
 * 通过CAS操作完成自旋锁，A线程先进来调用mylock方法自己持有锁5分钟，B随后进来发现当前线程持有锁，
 * 不是null，所以只能通过自选等待，直到A释放锁后B随后抢到
 */
public class SpinLockDemo {

    //原子引用线程
    AtomicReference<Thread> atomicReference=new AtomicReference<>();

    public void mylock(){
        Thread thread=Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"\t come in ✌︎");
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }

    public  void myunlock(){
        Thread thread=Thread.currentThread();
        atomicReference.compareAndSet(thread,null);

        System.out.println(Thread.currentThread().getName()+"\t myunck()");
    }

    public static void main(String[] args) {


        SpinLockDemo spinLockDemo = new SpinLockDemo();

        new Thread(()->{
            spinLockDemo.mylock();
            try{ TimeUnit.SECONDS.sleep(5); }catch (InterruptedException e){e.printStackTrace();}
            spinLockDemo.myunlock();
        },"AA").start();


        try{ TimeUnit.SECONDS.sleep(1); }catch (InterruptedException e){e.printStackTrace();}
        new Thread(()->{
            spinLockDemo.mylock();
            spinLockDemo.myunlock();
        },"BB").start();
    }
}
